<template>
  <div class="bg-[white] w-full h-full pt-[40px] px-[40px] text-base flex flex-col">
    <!-- 搜索区域 -->
    <div class="flex flex-wrap justify-start items-center gap-4 mb-6">
      <InputText type="text" label="设备名称" placeholder="请输入设备名称" class="w-[290px]" v-model="searchInfo.name" />
      <Button type="primary" content="查询" @click="getData">
        <template #icon>
          <IconSvg name="search" class="w-[18px] h-[18px]"></IconSvg>
        </template>
      </Button>
      <Button content="重置" @click="resetSearch">
        <template #icon>
          <IconSvg name="refresh" class="w-[15px] h-[15px]"></IconSvg>
        </template>
      </Button>
    </div>

    <!-- 表格区域 -->
    <div class="mt-[20px] flex-1 overflow-auto">
      <div class="flex justify-start items-center mb-4">
        <Button type="primary" content="新增" @click="openAddModel" v-perm="'device:add'">
          <template #icon>
            <IconSvg name="add" class="w-[18px] h-[18px]"></IconSvg>
          </template>
        </Button>
      </div>

      <DataTable :dataSource="tableData" :columns="tableColumns" class="mt-[20px]">
        <template #categoryname="{ item }">
          <a @click="handleLook(item)" class="text-[#165dff] cursor-pointer">查看</a>
        </template>
        <template #action="{ item }">
          <a @click="handleEdit(item)" class="text-[#165dff] cursor-pointer">修改</a>
          <a @click="handleDelete(item)" class="ml-2 text-red-500 cursor-pointer">删除</a>
        </template>
      </DataTable>
    </div>

    <!-- 分页区域 -->
    <div class="flex justify-end items-center my-4">
      <label class="font-medium mr-4">共{{ pageData.total }}条</label>
      <PaginationBasic :total="pageData.total" :page-size="pageData.pageSize" v-model:current="pageData.currentPage"
        @onPageChange="handlePageChange" />
    </div>

    <!-- 新增/修改模态框 -->
    <Model :show="showAddModel" @close="handleCancel">
      <template #header>
        <h3>{{ isAdd ? '添加赋码设备' : '修改赋码设备' }}</h3>
      </template>
      <template #body>
        <div class="flex flex-col gap-[15px]">
          <!-- 公共字段 -->
          <InputText type="text" label="设备名称" placeholder="请输入设备名称" class="w-[360px]" v-model="addInfo.devicename"
            label-width="60px" />
          <InputText type="number" label="设备数量" placeholder="请输入设备数量" class="w-[360px]" v-model="addInfo.quantity"
            label-width="60px" min="1" />

          <!-- 新增特有字段 -->
          <template v-if="isAdd">
            <InputSelect label="品类型号" label-width="60px" class="w-[360px] mr-[20px]"
              v-model="addInfo.useidentificationid" @change="handleModelChange(addInfo.useidentificationid)">
              <option v-for="item in useidentificationid" :key="item.value" :value="item.value">
                {{ item.label }}
              </option>
            </InputSelect>
            <InputSelect label="赋码规则" label-width="60px" class="w-[360px] mr-[20px]" v-model="addInfo.useruleid">
              <option v-for="item in useruleid" :key="item.value" :value="item.value">
                {{ item.label }}
              </option>
            </InputSelect>

          </template>
        </div>
      </template>
      <template #footer>
        <div class="flex justify-around">
          <Button content="取消" @click="handleCancel"></Button>
          <Button type="primary" content="确定" @click="handleConfirm"></Button>
        </div>
      </template>
    </Model>
    <Model :show="showLookModel" @close="handleLookClose">
      <template #header>
        <h3>标识详情</h3>
      </template>
      <template #body>
        <div class="p-4 max-h-[500px] overflow-auto-y-auto">
          <!-- 按逗号分割后遍历显示 -->
          <div v-for="(code, index) in lookInfoList" :key="index" class="mb-1 break-all">
            {{ code }}
          </div>
        </div>
      </template>
      <template #footer>
        <div class="flex justify-around">
          <Button content="关闭" @click="handleLookClose"></Button>
        </div>
      </template>
    </Model>
  </div>
</template>

<script setup>
// 组件导入
import InputText from "../../components/InputText.vue";
import InputSelect from "../../components/InputSelect.vue";
import Button from "../../components/Button.vue";
import IconSvg from "../../components/IconSvg.vue";
import DataTable from "../../components/DataTable.vue";
import Model from "../../components/Model.vue";
import PaginationBasic from "../../components/PaginationBasic.vue";
import Message from "../../components/Message/Message.js";
import { ref, onMounted, computed } from "vue";
import axios from "../../axios/axios.js";


// 数据源定义
const useidentificationid = ref([]); // 品类型号列表
const useruleid = ref([]); // 赋码规则列表
const type = ref([]); // 设备类型列表
const tableData = ref([]); // 表格数据
const searchInfo = ref({ name: '' }); // 搜索条件
const pageData = ref({ currentPage: 1, total: 0, pageSize: 10 }); // 分页数据

// 模态框相关状态
const showAddModel = ref(false);
const addInfo = ref({});
const operateItem = ref(null);
const isAdd = ref(false);

// 查看详情相关状态
const showLookModel = ref(false);
const lookInfo = ref('');
const lookInfoList = computed(() => {
  // 按逗号分割并过滤空值
  return lookInfo.value ? lookInfo.value.split(',').filter(item => item.trim()) : [];
});
const handleLookClose = () => {
  showLookModel.value = false;
  lookInfo.value = '';
};

// 表格列配置
const tableColumns = ref([
  { key: 'id', title: '编号', dataIndex: 'id', width: 60 },
  { key: 'devicename', title: '设备名称', dataIndex: 'devicename' },
  { key: 'useidentificationname', title: '使用标识', dataIndex: 'useidentificationname' },
  { key: 'categoryname', title: '标识', dataIndex: 'categoryname' },
  { key: 'quantity', title: '数量', dataIndex: 'quantity' },
  { key: 'createtime', title: '创建时间', dataIndex: 'createtime' },
  { key: 'action', title: '操作', dataIndex: 'action' }
]);

// 分页变化处理
const handlePageChange = (page) => {
  pageData.value.currentPage = page;
  getData();
};


// 编辑操作
const handleEdit = (item) => {
  isAdd.value = false;
  operateItem.value = item;
  showAddModel.value = true;
  addInfo.value = {
    devicename: item.devicename,
    quantity: item.quantity,
    type: item.type,
  };
};

const selectedModel = ref(null);
// 品类型号选择变化处理
const handleModelChange = (id) => {
  const numericId = Number(id); // 转为数字类型（根据实际数据类型调整）
  const selectedModel = useidentificationid.value.find(item => item.value == numericId);
  if (selectedModel) {
    addInfo.value.type = selectedModel.type;
  } else {
    console.warn(`未找到 id 为 ${id} 的模型`);
  }
};
// 查看操作
const handleLook = (item) => {
  const identificationInfo = tableData.value.find(
    info => info.value === item.tableData
  );

  if (identificationInfo) {
    // 保存要显示的信息
    lookInfo.value = item.identificationlist;
    // 显示模态框
    showLookModel.value = true;
  } else {
    Message.info('未找到对应的品类型号信息');
  }
};


// 删除操作
const handleDelete = (item) => {
  if (window.confirm(`确定要删除设备"${item.devicename}"吗？此操作不可撤销！`)) {
    axios.get(`/api/codingdevice/delete?id=${item.id}`)
      .then(res => {
        if (res.data.Code === "200") {
          Message.success('删除成功');
          getData();
        } else Message.warn(res.data.Msg || '删除失败');
      })
      .catch(() => Message.error('删除失败，请重试'));
  }
};

// 确认提交（新增/修改）
const handleConfirm = () => {
  // 表单验证
  if (!addInfo.value.devicename?.trim()) {
    Message.warn('请输入设备名称');
    return;
  }
  if (!addInfo.value.quantity || addInfo.value.quantity <= 0) {
    Message.warn('请输入有效的数量（大于0）');
    return;
  }
  if (isAdd.value) {
    if (!addInfo.value.useidentificationid) {
      Message.warn('请选择品类型号');
      return;
    }
    if (!addInfo.value.useruleid) {
      Message.warn('请选择赋码规则');
      return;
    }
  }

  // 构建提交数据
  const submitData = {
    devicename: addInfo.value.devicename,
    useidentificationid: addInfo.value.useidentificationid,
    useruleid: addInfo.value.useruleid,
    quantity: addInfo.value.quantity,
    type: addInfo.value.type,
    ...(isAdd.value ? {} : { id: operateItem.value.id })
  };

  // 提交请求
  const url = isAdd.value ? '/api/codingdevice/save' : '/api/codingdevice/update';
  axios.post(url, submitData)
    .then(res => {
      if (res.data.Code === "200") {
        Message.success(isAdd.value ? '设备添加成功' : '设备修改成功');
        showAddModel.value = false;
        getData();
      } else Message.warn(res.data.Msg || (isAdd.value ? '添加失败' : '修改失败'));
    })
    .catch(() => Message.error(`${isAdd.value ? '添加' : '修改'}失败，请重试`));
};

// 取消操作
const handleCancel = () => {
  showAddModel.value = false;
  addInfo.value = {};
  operateItem.value = null;
};

// 重置搜索
const resetSearch = () => {
  searchInfo.value = { name: '' };
  pageData.value.currentPage = 1;
  getData();
};

// 获取设备列表数据
const getData = () => {
  let url = `/api/codingdevice/select?pageNum=${pageData.value.currentPage}&pageSize=${pageData.value.pageSize}`;
  if (searchInfo.value.name?.trim()) {
    url += `&name=${encodeURIComponent(searchInfo.value.name.trim())}`;
  }
  if (searchInfo.value.category) {
    url += `&category=${searchInfo.value.category}`;
  }


  axios.get(url)
    .then(res => {
      if (res.data.Code === "200") {
        tableData.value = res.data.Data.records || [];
        pageData.value = {
          ...pageData.value,
          total: res.data.Data.total || 0,
          pageSize: res.data.Data.size || 10,
        };
      } else {
        Message.warn(res.data.Msg || '获取设备列表失败');
        tableData.value = [];
        pageData.value.total = 0;
      }
    })
    .catch(() => Message.error('网络错误，无法获取设备列表'));
};

onMounted(() => {
  // 只保留设备列表的初始化加载
  getData();
});
// 打开新增模态框 - 新增时加载数据
const openAddModel = () => {
  isAdd.value = true;
  showAddModel.value = true;
  addInfo.value = {};

  // 点击新增时才加载品类型号
  axios.get("/api/identify/selectall").then(res => {
    if (res.data.Code === "200") {
      useidentificationid.value = res.data.Data.map(item => ({
        value: item.id,
        label: item.name,
        type: item.type
      }));
    }
  });

  // 点击新增时才加载赋码规则
  axios.get("/api/codingrule/selectall").then(res => {
    if (res.data.Code === "200") {
      useruleid.value = res.data.Data.map(item => ({
        value: item.id,
        label: item.name
      }));
    }
  });
};
</script>

<style scoped></style>